package com.fengxu.myrule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
*@Description 自定义负载均衡规则的实现类
*@Author 风珝
*@Date 2021/1/13 21:45
*@Version 1.0.0
*/
public class CustomRule extends AbstractLoadBalancerRule {

    private AtomicInteger nextCount;

    public CustomRule() {
        this.nextCount = new AtomicInteger(0);
    }

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {
        // ignore
    }

    @Override
    public Server choose(Object o) {
        ILoadBalancer loadBalancer = this.getLoadBalancer();
        List<Server> allServers = loadBalancer.getAllServers();
        List<Server> reachableServers = loadBalancer.getReachableServers();
        Server server = null;
        if(allServers.size() != 0 || reachableServers.size() != 0)
        {
            int cur;
            int next;
            do{
                cur = nextCount.get();
                next = cur + 1;
            }while (!nextCount.compareAndSet(cur,next));

            if(allServers.size() >= 2 ){
                if(next % 3 == 0){
                    return allServers.get(1);
                } else {
                    return allServers.get(0);
                }
            } else {
                return allServers.get(0);
            }
        }
        return null;
    }
}
